package cn.wolfcode.shop.web.exception;

import cn.wolfcode.shop.exception.GlobalException;
import cn.wolfcode.shop.result.CodeMsg;
import cn.wolfcode.shop.web.result.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @ControllerAdvice 对Controller的增强 标签
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler({BindException.class, GlobalException.class})
    @ResponseBody
    public Result<CodeMsg> handleException(Exception e){
        if (e instanceof BindException) {
            BindException bex = (BindException) e;
            String defaultMessage = bex.getAllErrors().get(0).getDefaultMessage();
            return Result.error(CodeMsg.PARAM_ERROR.fillArgs(defaultMessage));
        }else if(e instanceof GlobalException){
            GlobalException bex = (GlobalException) e;
            return Result.error(((GlobalException) e).getCodeMsg());

        }else {
            return null;
        }
    }
}
